package com.haixinga.commbiz.member.ctrl.anno;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.alibaba.fastjson.JSONObject;
import com.haixinga.commbiz.commons.biz.ITokenService;
import com.haixinga.commbiz.commons.entity.MemberUser;
import com.haixinga.commbiz.commons.vo.ApiRes;
import com.haixinga.commbiz.member.ctrl.CommonCtrl;
import com.haixinga.commbiz.member.utils.MemberPropKit;
import com.haixinga.commbiz.commons.constants.CS;
import com.haixinga.commbiz.commons.exception.BizException;
import com.haixinga.commbiz.commons.service.MemberUserService;
import com.haixinga.commbiz.commons.utils.StringKit;
import com.haixinga.commbiz.member.vo.MemberLoginUserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("anno/auth")
public class AuthController extends CommonCtrl {

	private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

	@Autowired private MemberUserService memberUserService;


	/** code 换取 系统的iToken  **/
	@RequestMapping(value = "/code2token", method = RequestMethod.POST)
	public ApiRes code2token() throws BizException {


		String code = getValStringRequired("code");

		//1. code换取用户信息; 获取wxOpenId
		WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
		config.setAppid(MemberPropKit.getWxMiniConfig().getAppid());
		config.setSecret(MemberPropKit.getWxMiniConfig().getSecret());
		WxMaService wxService = new WxMaServiceImpl();
		wxService.setWxMaConfig(config);


		String openId = "";
		String sessionKey = "";
		String unionId = "";

		try {
			WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
			openId = session.getOpenid();
			sessionKey = session.getSessionKey();
			unionId = session.getUnionid();  //当用户未关注公众号时， unionId为空

		} catch (Exception e) {
			logger.error("", e);
			throw new BizException("获取用户信息失败！");
		}

		MemberUser user = null;
		if(StringKit.isNotEmpty(unionId)){ //说明用户已关注公众号
//			user = memberUserService.selectBy3rdId(unionId, CS.AUTH_TYPE.WX_UNION_ID);
		}

		if(user == null){ //未关注公众号 通过小程序的openId 查询
//			user = memberUserService.selectBy3rdId(openId, CS.AUTH_TYPE.WX_MINI);
		}

		//仍然为空， 说明是游客
		if(user == null){
			JSONObject result = new JSONObject();
			result.put(CS.ACCESS_TOKEN_NAME, ""); //游客 token为空。
			return ApiRes.ok(result);
		}

		//设置缓存对象信息
		MemberLoginUserVO loginUserVO = new MemberLoginUserVO();
		loginUserVO.setUserId(user.getMuId());
		loginUserVO.setUsername(user.getRealname());
		loginUserVO.setMemberUser(user);

		loginUserVO.setWxOpenId(openId);
		loginUserVO.setWxUnionId(unionId);
		loginUserVO.setWxSessionKey(sessionKey);

		//生成iToken 并放置到缓存
		String iToken = StringKit.getUUID();  //TODO 1 更改为更安全的方式
		ITokenService.processTokenCache(loginUserVO, iToken); //处理token 缓存信息

		JSONObject result = new JSONObject();
		result.put(CS.ACCESS_TOKEN_NAME, iToken);
		result.put("isBindTelphone", StringKit.isNotEmpty(user.getTelphone()));

		return ApiRes.ok(result);
	}

}
